<template>
  <PerfectTableComponent
    v-bind="$props"
    v-model:multipleSelection="multipleSelection"
    :loadTableList="loadTableList"
    :changePageSize="changePageSize"
    :changePage="changePage"
    :removeQueryField="removeQueryField"
    :clearQuery="clearQuery"
    v-model:query="query"
    title="物料批次"
    ref="tableRef"
    :queryFormHeaders="queryFormHeaders"
    :table="table"
    :tableColumns="tableColumns"
    :showTableIndex="false"
    :operatorColumnWidth="300"
    :baseUrl="urls.API_URL_BACKSTAGE_WMS_WMSMATERIALBATCH"
    v-model:form="form"
    :formHeader="formHeader"
    @beforeAddRow="beforeAddRow"
    @afterLoadDataSuccessInEditRow="afterLoadDataSuccessInEditRow"
    @beforeFormSubmit="beforeFormSubmit"
  >
    <!-----------------------------表格自定义列----------------------------------------->
    <!--所属栏目1-->
    <template #table_column_materialName="scope: any">
      {{ scope.row.material != null ? scope.row.material.name : '' }}
    </template>
    <template #table_column_materialTypeName="scope: any">
      {{ scope.row.material != null ? scope.row.material.materialType.name : '' }}
    </template>
    <!-----------------------------表格自定义列（操作列）----------------------------------------->
    <template #table_operator_left="scope">
      <el-button
        @click="
          router.push({
            path: '/backstage/wms/MaterialInventoryDetail',
            query: {
              materialBatchId: scope.row.id
            }
          })
        "
        type="primary"
        size="small"
        icon="Box"
        plain
        >库存管理</el-button
      >
    </template>
  </PerfectTableComponent>
</template>

<script setup lang="ts">
import PerfectTableComponent from '@/components/base/table/PerfectTableComponent.vue';
import { nextTick, onMounted, provide, reactive, ref, watch } from 'vue';
import useTableList from '@/api/hooks/useTableList';
import type { FormHeader, ResponseData, TableColumn } from '@/types/interface/base_interface';
import urls from '@/api/request/urls';
import { getDict } from '@/api/dict';
import type { MaterialBatch } from '@/types/interface/wms_interface';
import Request from '@/api/request/request';
import { useRouter } from 'vue-router';
// 导入路由
const router = useRouter(); // 创建路由对象

// 表格工具必备参数
//设置为不立即加载，本组件要供其他组件使用，避免其他组件打开时多次刷新。
const { table, query, loadTableList, removeQueryField, setQueryField, clearQuery, changePageSize, changePage } = useTableList(
  urls.API_URL_BACKSTAGE_WMS_WMSMATERIALBATCH
  // true,
  // {},
  // false
);
// 将表格刷新函数传到子容器
provide('loadTableList', loadTableList);
// 复选框选择的记录row集合，提供给父组件调用，例如在这个表格上用对话框再进行封装。
const multipleSelection = defineModel<any[]>('multipleSelection', {
  required: false,
  default: []
});
// 接收父组件（因为本组件供其他组件调用，因此封装）传递过来的值
interface Props {
  showToolBar?: Boolean; // 是否显示表格工具栏，默认显示
  showOperatorColumn?: Boolean; // 是否显示表格右侧的操作栏，默认显示
  showAddNewButton?: Boolean; // 在表格工具栏是否显示新增按钮
  showDeleteButton?: Boolean; // 是否显示删除按钮，如果不显示则整个表格插件都不显示
  showEditButton?: Boolean; //  是否显示编辑按钮，如果不显示则整个表格插件都不显示
  operatorColumnWidth?: number; // 表格右侧操作了大小
  dialogConfirmButtonText?: string; // 确认按钮上的文字
  materialIdOfQuery?: string; //物料id，不是必须，但是如果是必须则默认物料批次的查询条件固定位物料
  allowEditTableCell?: Boolean; //是否允许表格可以双击单元格编辑
}
const props = withDefaults(defineProps<Props>(), {
  showToolBar: () => Boolean(true), //默认显示
  operatorColumnWidth: 300
});
//监听物料id,如果存在则默认显示该物料，查询条件的物料写死。
// watch(
//   () => props.materialIdOfQuery,
//   async (newVal: any, oldVal: any) => {
//     if (props.materialIdOfQuery && props.materialIdOfQuery.length > 0) {
//       query.value['material.id'] = props.materialIdOfQuery;
//     } else {
//       delete query.value['material.id'];
//     }
//     // await nextTick();
//     loadTableList();
//   },
//   { immediate: true, deep: true }
// );

//查询==========================================================
const queryFormHeaders = ref<FormHeader[]>([]);

//表格==========================================================
// 表格插件ref对象1
const tableRef = ref();

//表格列
// 定义表格所有的列字段信息
const tableColumns = ref<TableColumn[]>([]);

//表单==========================================================
//表单对象
const form = ref<MaterialBatch>({});
//表单元素类型
const formHeader = ref<FormHeader[]>([]);

onMounted(async () => {
  //定义优先级选项。放在mounted中执行时，要将引用改变量的属性也放进来。
  const lockDict = await getDict('锁定状态', 'boolean');
  queryFormHeaders.value = [
    // 查询表单
    {
      prop: 'material.name',
      label: '物料名称'
    },
    {
      prop: 'batchNumber',
      label: '物料批次号'
    },
    {
      prop: 'manuFacturer',
      label: '生产厂家'
    },
    {
      prop: 'isLock',
      label: '是否锁定',
      type: 'select',
      list: lockDict
    }
  ];
  if (query.value['material.id']) {
    //如果在父组件传递了物料id过来，则显示查询条件
    queryFormHeaders.value.unshift({
      prop: 'material.id',
      label: '物料id',
      readonly: true
    });
  }
  //表格对象
  tableColumns.value = [
    {
      label: '物料名',
      prop: 'materialName',
      type: 'custom',
      width: 150,
      fixed: true
    },
    {
      label: '物料类别',
      prop: 'materialTypeName',
      type: 'custom',
      width: 150,
      fixed: true
    },
    {
      label: '物料批次',
      prop: 'batchNumber',
      width: 130
    },
    {
      label: '生产厂家',
      prop: 'manuFacturer',
      width: 130
    },
    {
      label: '生产日期',
      prop: 'productionDate',
      width: 100
    },
    {
      label: '进货数量',
      prop: 'purchaseQuantity'
    },
    {
      label: '入库数量',
      prop: 'storedQuantity'
    },
    {
      label: '总库存数',
      prop: 'totalInventory'
    },
    {
      label: '锁定数量',
      prop: 'lockQuantity'
    },
    {
      label: '锁定状态',
      prop: 'isLock',
      width: 100,
      type: 'dict',
      dict: lockDict
    },
    {
      label: '创建时间',
      prop: 'createTime',
      width: 180
    }
  ];
  // 添加编辑表单
  formHeader.value = [
    {
      label: '物料',
      prop: 'materialId',
      propLabel: 'materialName',
      type: 'material',
      action: 'post',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '物料',
      prop: 'materialId',
      propLabel: 'materialName',
      type: 'material',
      action: 'put',
      readonly: true
    },
    {
      label: '批次编码',
      prop: 'batchNumber',
      action: 'post',
      placeholder: '如果为空则系统自动生成',
      rules: [
        {
          max: 50,
          message: '长度在不能超过50个字符',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '生产厂家',
      prop: 'manuFacturer',
      rules: [
        {
          max: 50,
          message: '长度在不能超过50个字符',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '生产日期',
      prop: 'productionDate',
      type: 'date'
    },
    {
      label: '进货数量',
      prop: 'purchaseQuantity',
      type: 'number',
      action: 'post',
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '锁定状态',
      prop: 'isLock',
      type: 'select',
      list: lockDict,
      rules: [
        {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '进货数量',
      prop: 'purchaseQuantity',
      type: 'label',
      action: 'put'
    },
    {
      label: '入库数量',
      prop: 'storedQuantity',
      type: 'label',
      action: 'put'
    },
    {
      label: '库存数量',
      prop: 'totalInventory',
      type: 'label',
      action: 'put'
    },
    {
      label: '锁定数量',
      prop: 'lockQuantity',
      type: 'label',
      action: 'put'
    }
  ];
});
//在添加行的动作以前
const beforeAddRow = async () => {
  //传入初始值
  form.value = {
    isLock: false
  };
};
//在编辑行读取后端记录后需要修改的地方
const afterLoadDataSuccessInEditRow = async (formEdit: MaterialBatch) => {
  //重新封装表单对象的值
  if (formEdit.material != null) {
    formEdit.materialId = formEdit.material.id;
    formEdit.materialName = formEdit.material.name;
  }
};
//在表单提交前对对象进行封装
//在表单提交前对对象进行封装
const beforeFormSubmit = () => {
  if (form.value.materialId != null) {
    form.value.material = {
      id: form.value.materialId
    };
  }
};
//清空表格选中的复选框
const clearSelection = () => tableRef.value!.clearSelection();
defineExpose({
  clearSelection,
  clearQuery,
  setQueryField,
  loadTableList
});
</script>

<style scoped></style>
